package com.bytedance.frameworks.baselib.network.http.c;

import com.bytedance.frameworks.baselib.network.dispatcher.IRequest.Priority;
import com.bytedance.frameworks.baselib.network.dispatcher.RequestQueue;
import com.bytedance.retrofit2.PriorityLevel;
import com.bytedance.retrofit2.CallbackRunnable;
import com.bytedance.retrofit2.SsCall;

import java.util.concurrent.Executor;

public final class SsHttpExecutor implements Executor {
    private static RequestQueue sRequestQueue = RequestQueue.getInstance();

    public SsHttpExecutor() {

    }

    public final void execute(Runnable runnable) {
        if (runnable != null) {
            Priority priority = Priority.NORMAL;
            boolean isStreaming = false;
            if (runnable instanceof CallbackRunnable) {
                CallbackRunnable callbackRunnable = (CallbackRunnable) runnable;
                PriorityLevel priorityLevel = SsCall.getServiceMethod(callbackRunnable.ssHttpCall).priorityLevel;
                if (priorityLevel != null) {
                    switch (priorityLevel) {
                        case LOW: {
                            priority = Priority.LOW;
                            break;
                        }
                        case NORMAL: {
                            priority = Priority.NORMAL;
                            break;
                        }
                        case HIGH: {
                            priority = Priority.HIGH;
                            break;
                        }
                        case IMMEDIATE: {
                            priority = Priority.IMMEDIATE;
                            break;
                        }
                        default:
                            priority = Priority.NORMAL;
                            break;
                    }
                }
                isStreaming = SsCall.getServiceMethod(callbackRunnable.ssHttpCall).isStreaming;
            }

            SsHttpRequest ssHttpRequest = new SsHttpRequest("SsHttpExecutor", priority, runnable);
            if (SsHttpExecutor.sRequestQueue == null) {
                SsHttpExecutor.sRequestQueue = RequestQueue.getInstance();
            }
            if (isStreaming) {
                SsHttpExecutor.sRequestQueue.downloadRequestEnqueue(ssHttpRequest);
            }else {
                SsHttpExecutor.sRequestQueue.apiRequestEnqueue(ssHttpRequest);
            }
        }
    }
}

